package com.imdada.open.platform.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.imdada.open.platform.client.internal.req.common.ApiResponse;
import com.imdada.open.platform.client.internal.resp.order.AddOrderResp;
import com.imdada.open.platform.config.Configuration;
import com.imdada.open.platform.client.internal.req.order.AddOrderReq;
import com.imdada.open.platform.client.internal.req.order.internal.ProductDetail;
import com.imdada.open.platform.exception.RpcException;
import lombok.extern.slf4j.Slf4j;

import java.util.Collections;
import java.util.Objects;

@Slf4j
public final class AddOrderUtils {

    /**
     * 构建测试发单参数(请根据自己实际情况调整参数)
     */
    public static AddOrderReq buildOrderDetail4Demo(String orderNo) {
        ProductDetail productDetail = ProductDetail.builder()
                .skuName("高原风干牛肉干（麻辣味）250克/袋 | 250克")
                .count(2.0)
                .srcProductNo("xxx")
                .unit("件")
                .build();

        return AddOrderReq.builder()
                .shopNo(Configuration.getInstance().getShopNo())
                .originId(orderNo)
                .cityCode("021")
                .cargoPrice(50.0)
                .cargoNum(1)
                .tips(1.0)
                .info("备注信息")
                .cargoWeight(3.2)
                .isUseInsurance(0)
                .prepay(0)
                .finishCodeNeeded(0)
                .cargoType(50)
                .invoiceTitle("invoiceTitle")
                .receiverName("张三")
                .receiverAddress("上海市浦东新区东方渔人码头")
                .receiverPhone("18500000000")
                .receiverLat(31.257801)
                .receiverLng(121.538842)
                .callback(Configuration.getInstance().getCallback())
                .pickUpPos("1号货架")
                .productList(Collections.singletonList(productDetail))
                .build();
    }

    /**
     * 处理结果
     */
    public static AddOrderResp parseAddOrderResponse(String rpcResult, String errMsgPrefix) throws RpcException {
        ApiResponse<AddOrderResp> response = JSON.parseObject(rpcResult, new TypeReference<ApiResponse<AddOrderResp>>() {
        });
        // 根据status判断是否执行成功
        if (Objects.nonNull(response) && response.success()) {
            return response.getResult();
        } else {
            throw new RpcException(String.format("%s : %s", errMsgPrefix, response.getMsg()));
        }
    }

}
